import { CloseCircleOutlined, SearchOutlined } from "@ant-design/icons";
import {
  BaseEdge,
  EdgeLabelRenderer,
  getBezierPath,
  useReactFlow,
} from "@xyflow/react";
import { Button } from "antd";
import { memo, useState } from "react";

function CustomEdge({
  id,
  sourceX,
  sourceY,
  sourcePosition,
  targetX,
  targetY,
  targetPosition,
}) {
  const { setEdges } = useReactFlow();
  const [edgePath, labelX, labelY] = getBezierPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition,
  });
  const [isVisible, setIsVisible] = useState(false);

  return (
    <>
      <defs>
        <marker
          id="arrow"
          viewBox="0 0 20 20"
          refX="10"
          refY="10"
          markerWidth="10"
          markerHeight="10"
          orient="auto-start-reverse"
        >
          <path
            d="M 0 5 L 10 10 L 0 15"
            fill="none"
            stroke="#D0D5DD"
            strokeWidth="2"
            strokeLinejoin="round"
          />
        </marker>
      </defs>

      {/* 添加一个透明的、较宽的路径来处理鼠标事件 */}
      <BaseEdge
        id={id}
        path={edgePath}
        style={{
          strokeWidth: 2,
          stroke: "#D0D5DD"
        }}
        markerEnd="url(#arrow)"
      />
      <path
        d={edgePath}
        fill="none"
        strokeWidth={20}
        stroke="transparent"
        onMouseEnter={() => setIsVisible(true)}
        onMouseLeave={() => setIsVisible(false)}
      />
      <EdgeLabelRenderer>
        <Button
          onMouseEnter={() => setIsVisible(true)}
          onMouseLeave={() => setIsVisible(false)}
          style={{
            transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
            pointerEvents: "all",
            display: isVisible ? "inline-block" : "none",
            zIndex: 100000
          }}
          onClick={() => {
            setEdges((es) => es.filter((e) => e.id !== id));
          }}
          shape="circle"
          size="middle"
          icon={<CloseCircleOutlined style={{ color: "#c1c1c1", marginTop: 2 }} />}
        />
      </EdgeLabelRenderer>
    </>
  );
}

export default memo(CustomEdge)